<template>
  <div class="ai-marketing">
    <a-row justify="space-between" align="middle">
      <a-col>
        <!-- 标题 -->
        <div class="flex align-center">
          <RouteTitle :isBack="true" />
        </div>
      </a-col>
    </a-row>
    <div class="marketing-content">
      <!-- 左侧 -->
      <div class="content-left relative">
        <div class="list-wrapper">
          <div class="header">
            <div>
              <span class="text-red-6">*</span>
              <span class="font-bold">选择场景</span>
            </div>
          </div>
          <!-- 场景列表 -->
          <div ref="appListRef" class="app-list">
            <template v-for="app in appList" :key="app.id">
              <!-- 为展开 -->
              <div :id="'app_' + app.id" class="app-item" v-if="hasAppId(app)"
                :class="currentAppId == app.id ? 'active-app' : ''" @click="changeApp(app)">
                <div class="app-item-left">
                  <div class="app-icon-wrapper">
                    <img :src="app.icon" class="app-icon" />
                  </div>
                  <div class="overflow-hidden">
                    <div class="font-bold">{{ app.name }}</div>
                    <div class="fs-12 text-gray-6 mt-5 text-ellipsis">
                      {{ app.info }}
                    </div>
                  </div>
                </div>
                <caret-down-filled v-if="expendAppId" />
              </div>
            </template>
          </div>
        </div>
        <!-- 展开 -->
        <div class="app-form-area" v-if="expendAppId">
          <div class="form-wrapper">
            <!-- 表单 -->
            <appForm ref="appFormRef" :edit_data="updateTextData" :user_form="currentForm" />
          </div>
          <div class="btn-area">
            <a-button type="primary" style="width: 90%; font-size: 13px" size="large" :loading="spinning"
              @click="generate">一键生成</a-button>
          </div>
        </div>
        <div class="loading" v-if="spinning">
          <loading-outlined />
          <span class="loading-text"></span>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="content-right">
        <div class="batch-area" v-if="textArticleList.length > 1">
          <a-checkbox :disabled="isTextDisabled || txtBtbDisabled" :checked="isTextAllChecked"
            @change="textSelectAll">全选</a-checkbox>
          <a-button :disabled="isTextDisabled || txtBtbDisabled" type="danger" size="small"
            @click="textDelete">批量删除</a-button>
          <a-button type="primary" size="small" :disabled="isTextDisabled || txtBtbDisabled"
            @click="batchTextAdd">批量添加到文案库</a-button>
          <a-button type="primary" size="small" :disabled="isTextDisabled || txtBtbDisabled"
            @click="batchTextOperation('mixedCutCreat')">批量剪辑</a-button>
          <a-button type="primary" size="small" :disabled="isTextDisabled || txtBtbDisabled"
            @click="batchTextOperation('OneClickClip')" v-permissionOneClickClip>批量一键成片</a-button>
        </div>
        <template v-if="textArticleList.length">
          <!-- 文章列表 -->
          <div class="relative" v-for="(item, index) in textArticleList" :key="item.id">
            <div class="checkbox" v-if="textArticleList.length > 1">
              <a-checkbox :disabled="isTextDisabled || txtBtbDisabled" :checked="textCheckedId.includes(item.id)"
                @change="textChecked(item.id)" />
            </div>
            <!-- 文章卡片 -->
            <Article class="mb-10" @updateList="updateTextList" :isMultiple="isTextMultiple"
              v-model:articleData="textArticleList[index]"></Article>
          </div>
        </template>
        <div v-else class="empty">
          <a-empty>
            <template #description>
              <span class="text-gray-6">等待生成</span>
            </template>
          </a-empty>
        </div>
      </div>
    </div>
    <List v-model:visible="listVisible" @onPreview="onPreview"></List>
    <!-- 保存到文案库弹窗组件 -->
    <BatchCollect ref="batchTextadd" :articles="chooseTextArticle"></BatchCollect>
  </div>

  <!-- 充值弹窗 -->
  <vipModal ref="vipModalRef" :visible="vipVisible" @close="vipVisible = false"></vipModal>


</template>
<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import store from "@/store";
import request from "@/common/utils/request";
import { message, Modal } from "ant-design-vue";
import _ from "lodash";
import { useRoute, useRouter } from "vue-router";
import { CaretDownFilled, LoadingOutlined } from "@ant-design/icons-vue";
import appForm from "./components/appForm.vue"; //表单组件
import Article from "./components/articles.vue"; //文章卡片组件
import List from "./components/list.vue";
// 保存到文案库弹窗
import BatchCollect from "./components/batchCollect.vue";
import utils from '@/common/utils/utils'
// 充值弹窗
import vipModal from '@/socialMedia/Vip/vipModal.vue'
const vipModalRef = ref(null)
const vipVisible = ref(false)

const route = useRoute();
const router = useRouter();
let appList = ref([]);
let cateList = ref([]);
let currentForm = ref({});
let currentAppId = ref(0);
let currentAppCateId = ref(0);
let expendAppId = ref(0);
let appListRef = ref();
let appListScrollHeight = ref(0);
let appListClientHeight = ref(0);
let appFormRef = ref();
let textArticleList = ref([]);
let timer = ref();
let textCheckedId = ref([]);
let updateTextData = ref({});
let listVisible = ref(false);
let spinning = ref(false);
let collectVisible = ref(false);
const chooseTextArticle = computed(() => {
  return textArticleList.value.filter((v) =>
    textCheckedId.value.includes(v.id)
  );
});
const isTextDisabled = computed(() => {
  return Object.keys(updateTextData.value).length > 0;
});
let isTextAllChecked = computed(() => {
  return (
    textArticleList.value.length &&
    textCheckedId.value.length == textArticleList.value.length
  );
});
const txtBtbDisabled = computed(() => {
  return textArticleList.value.some((v) => v.status != 2);
});
const isTextMultiple = computed(() => {
  return textArticleList.value.length > 1;
});
const getCategoryList = async () => {
  const { applicationList } = await store.dispatch("GetSceneApps");
  let filterList = applicationList.filter((item) => item.is_social_media == 0);
  cateList.value = [].concat(filterList);
  getApplicationList();
};
const getApplicationList = async () => {
  const requests = cateList.value.map((item) => {
    return request
      .get("/work_ai", "/application/category/app_list", {
        is_industry: 0,
        cat_id: item.id,
        is_social_media: 0,
      })
      .then(({ app_list }) => {
        appList.value.push(...app_list);
        // lodash  数组 根据id  去重
        appList.value = _.uniqBy(appList.value, "id");
      });
  });

  await Promise.all(requests);
  nextTick(() => {
    if (route.query.cateId) {
      let user_form = appList.value.find(
        (item) => item.id == route.query.appId
      ).user_form;
      changeApp({
        id: route.query.appId,
        cat_id: route.query.cateId,
        user_form,
      });
    }
  });
};

getCategoryList();

// await getApplicationList()
const changeApp = (app) => {
  currentAppId.value = app.id;
  currentAppCateId.value = app.cat_id;

  if (expendAppId.value == app.id) {
    expendAppId.value = 0;
  } else {
    expendAppId.value = app.id;
  }

  setTimeout(() => {
    let appListClientHeight = appListRef.value.clientHeight;
    let appListScrollHeight = appListRef.value.scrollHeight;

    if (!expendAppId.value) {
      if (appListScrollHeight > appListClientHeight) {
        const appDom = document.getElementById("app_" + app.id);
        appDom.scrollIntoView({ behavior: "smooth", block: "center" });
      }
    }
  }, 400);

  currentForm.value = app.user_form;
};
const hasAppId = (item) => {
  if (expendAppId.value == 0) {
    return true;
  } else {
    return item.id == expendAppId.value;
  }
};
const listWrapperHeight = computed(() => {
  return expendAppId.value ? "146px" : "100%";
});
const generate = () => {

  appFormRef.value
    .validate()
    .then(async() => {

      try {
        // 查看用户的点数是否足够消耗
        await utils.aiTextGet()
        try {
          // 消耗规则
          const rule = await utils.consumptionPointRule()
          // 获取提示
          const content = utils.ruleTips({ res: rule, key: "ai_text_point" })
          // 弹出提示
          await utils.md({ content })
          // 弹窗确认消耗
        } catch (error) {
          return
        }
      } catch (error) {
        // 打开充值, 接着打开点数购买
        vipVisible.value = true
        vipModalRef.value && vipModalRef.value.openBuyVisible()
        return
      }

      textArticleList.value = [];
      spinning.value = true;
      let formRefData = appFormRef.value.formRef;
      let keyword =
        formRefData.keyword_type == "product"
          ? formRefData.product_keyword
          : formRefData.library_keyword;
      let keywordArr = keyword.split("\n").filter((item) => item.trim() != "");
      let user_form = {};
      for (const key in formRefData) {
        if (key.includes("value")) {
          user_form[key] = formRefData[key];
        }
      }
      let params = {
        application_category_id: currentAppCateId.value,
        application_id: currentAppId.value,
        // keyword_business_type: formRefData.keyword_type,
        // keyword_business_id: formRefData.product_id
        //   ? formRefData.product_id
        //   : 0,
        // keyword: keywordArr,
        generate_article_count: formRefData.count,
        user_form,
      };
      request
        .post("/work_ai", "/user/socialMedia/campaignTask/add", params)
        .then((res) => {
          let { key } = res.result;
          queryArticleProgress(key);
        })
        .catch((error) => {
          spinning.value = false;
        });
    })
    .catch((error) => {
      console.log(error);
      console.log(appFormRef.value.currentProduct);

      let errMsg = error.errorFields?.[0]?.errors?.[0] ?? "";
      if (errMsg) {
        message.error(errMsg);
      }
    });
};
const handleList = (list) => {
  list.forEach((item) => {
    let index = textArticleList.value.findIndex((v) => v.id == item.id);
    if (index == -1) {
      textArticleList.value.push(item);
    } else {
      textArticleList.value[index] = item;
    }
    if (item.status == 3) {
      message.error(item.status_msg);
      textArticleList.value = textArticleList.value.filter(
        (v) => v.status != 3
      );
    }
  });
};
const queryArticleProgress = (key) => {
  timer.value = setInterval(() => {
    request
      .get("/work_ai", "/user/socialMedia/campaignTask/progress", {
        key,
      })
      .then((res) => {
        let { status, campaign_task_log } = res.result;
        if (status == 2) {
          clearInterval(timer.value);
          spinning.value = false;
        }
        handleList(campaign_task_log);
      })
      .catch((err) => {
        spinning.value = false;
        clearInterval(timer.value);
      });
  }, 1000);
};
const onHistory = () => {
  listVisible.value = true;
};
const getDetail = (record) => {
  request
    .get("/work_ai", "/user/socialMedia/campaignTaskLog/info", {
      id: record.id,
    })
    .then((res) => {
      updateTextData.value = res.result;
      textArticleList.value = [
        {
          id: updateTextData.value.id,
          title: updateTextData.value.title,
          content: updateTextData.value.content,
          status: updateTextData.value.status,
          status_msg: updateTextData.value.status_msg,
          campaign_task_id: updateTextData.value.campaign_task_id,
        },
      ];
    })
    .finally(() => {
      spinning.value = false;
    });
};
const onPreview = (record) => {
  listVisible.value = false;
  spinning.value = true;
  getDetail(record);
};
const textDelete = () => {
  if (!textCheckedId.value.length) {
    return message.warning("请选择要删除的文章");
  }
  Modal.confirm({
    title: () => `确定要删除吗？`,
    okText: "确认",
    cancelText: "取消",
    centered: true,
    onOk() {
      request
        .del("/work_ai", "/user/socialMedia/campaignTaskLog/delete", {
          ids: textCheckedId.value,
          campaign_task_id: textArticleList.value[0].campaign_task_id,
        })
        .then((res) => {
          textArticleList.value = textArticleList.value.filter(
            (v) => !textCheckedId.value.includes(v.id)
          );
          textCheckedId.value = [];
          message.success("删除成功");
        });
    },
  });
};
const textChecked = (id) => {
  if (textCheckedId.value.includes(id)) {
    textCheckedId.value = textCheckedId.value.filter((v) => v != id);
  } else {
    textCheckedId.value.push(id);
  }
};
const textSelectAll = (e) => {
  if (e.target.checked) {
    textCheckedId.value = textArticleList.value.map((v) => v.id);
  } else {
    textCheckedId.value = [];
  }
};
let batchTextadd = ref(null);
const batchTextAdd = () => {
  if (!textCheckedId.value.length) {
    return message.warning("请选择要添加的文章");
  }
  batchTextadd.value && batchTextadd.value.showModal();
};
if (route.query.id) {
  getDetail({ id: route.query.id });
}
const goBack = () => {
  router.go(-1);
};
// 批量一键成片/批量剪辑
const batchTextOperation = (type) => {
  if (!textCheckedId.value.length) {
    return message.warning("请选择要剪辑的文章");
  }
  const filteredLists = textArticleList.value.filter((article) =>
    textCheckedId.value.includes(article.id)
  );
  const sceneCreationTexts = filteredLists?.map((text) => text.content);
  const sceneCreationTitles = filteredLists?.map((text) => text.title);
  store.commit("SET_SCENE_CREATION_TEXTS", sceneCreationTexts);
  store.commit("SET_SCENE_CREATION_TITLES", sceneCreationTitles);
  const routeConfig = {
    OneClickClip: {
      name: "OneClickClip",
      query: { sceneCreation: "sceneCreation" },
    },
    mixedCutCreat: {
      name: "mixedCutCreat",
      query: { type: 0, viewType: 2, sceneCreation: "sceneCreation" },
    },
  };

  router.push(routeConfig[type]);
};
</script>
<style lang="less" scoped>
.ai-marketing {
  height: 100%;
}
.marketing-content {
  position: relative;
  display: flex;
  margin-top: 16px;
  gap: 20px;
  height: calc(100% - 56px);
  .content-left {
    width: 456px;
    height: 100%;
    // background-color: #fff;
    .list-wrapper {
      background-color: #fff;
      border-radius: 10px;
      box-sizing: border-box;
      padding-bottom: 10px;
      //   padding: 10px;
      //   height: 100%;
      height: v-bind(listWrapperHeight);
      transition: all 0.3s;
      .header {
        margin-bottom: 10px;
        padding: 10px;
      }
    }
    // .list {

    .cate-item {
      padding: 10px;
    }
    .cate-item-title {
      font-size: 14px;
      margin-bottom: 10px;
    }
    .app-list {
      max-height: calc(100% - 50px);
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      gap: 20px;
      padding: 5px;
    }
    .app-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      padding: 37px 10px 37px 30px;
      box-sizing: border-box;
      overflow: hidden;
      height: 74px;
      border-radius: 6px;
      cursor: pointer;
      background-color: #f3f4fa;
      margin: 0 10px;
      &:hover {
        outline: 1px solid #1890ff;
      }
      .app-icon-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 42px;
        height: 42px;
        background-color: #fff;
        border-radius: 10px;
        flex-shrink: 0;
      }
      .app-icon {
        width: 30px;
        height: 30px;
      }
    }
    // }
  }
  .content-right {
    flex: 1;
    height: 100%;
    background-color: #fff;
    padding: 10px 20px;
    box-sizing: border-box;
    overflow-y: auto;
    border-radius: 10px;
  }
}
.text-red-6 {
  color: red;
  margin-right: 5px;
}
.active-app {
  outline: 1px solid #1890ff;
  background-color: #d5d5f6 !important;
}
.app-form-area {
  height: calc(100% - 161px - 70px);
  margin-top: 15px;
  border-radius: 10px;
}
.form-wrapper {
  height: 100%;
  background-color: #fff;
  overflow-y: auto;
  padding: 20px;
  box-sizing: border-box;
}
.app-item-left {
  display: flex;
  align-items: center;
  gap: 20px;
  overflow: hidden;
}
.btn-area {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  height: 70px;
  border-radius: 0 0 10px 10px;
  border-top: 1px solid #eaeaea;
}
.batch-area {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px;
  margin-bottom: 10px;
}
.checkbox {
  position: absolute;
  top: 10px;
  left: 6px;
  z-index: 100;
}
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
}
.loading {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99;
  background-color: rgba(255, 255, 255, 0.5);
  color: var(--ss-primary-color);
  .loading-text {
    margin-top: 10px;
    color: var(--ss-primary-color);
  }
}
</style>
